package cn.ydw.community.service.impl;

import cn.ydw.community.dao.DiscussPostDao;
import cn.ydw.community.entity.Comment;
import cn.ydw.community.dao.CommentDao;
import cn.ydw.community.service.CommentService;
import cn.ydw.community.util.CommunityConstant;
import cn.ydw.community.util.SensitiveWordsFilter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dw
 * @since 2020-10-18
 */
@Service
public class CommentServiceImp extends ServiceImpl<CommentDao, Comment> implements CommentService, CommunityConstant {

    @Autowired
    private CommentDao commentDao;

    @Autowired
    private SensitiveWordsFilter sensitiveFilter;

    @Autowired
    private DiscussPostDao discussPostDao;
    @Autowired
    private ElasticService elasticService;
    @Override
    public List<Comment> findCommentsByEntity(Page page, Integer entityType, Integer entityId) {
        return commentDao.selectCommentByEntity(page, entityType, entityId);
    }

    @Transactional(isolation= Isolation.READ_COMMITTED, propagation= Propagation.REQUIRED)
    @Override
    public int addComment(Comment comment) {
        if (comment == null){
            throw new IllegalArgumentException("参数不能为空!");
        }
        // 添加评论
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        int rows = commentDao.insert(comment);
        // 更新帖子评论数量
        if (comment.getEntityType() == ENTITY_TYPE_POST){
            Page<Object> page = new Page<>();
            commentDao.selectCommentByEntity(page,ENTITY_TYPE_POST, comment.getEntityId());
            discussPostDao.updateDiscussPostCommentCount(comment.getEntityId(), (int) page.getTotal());
            elasticService.save(discussPostDao.selectById(comment.getEntityId()));
        }
        return rows;
    }

    @Override
    public Comment findCommentById(int id) {
        return commentDao.selectById(id);
    }


}
